<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html>
<head>
<title>Menus &amp; toolbars in Tkinter</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="GUI, menu, toolbar, Tkinter, programming, Python, Linux">
<meta name="description" content="This part of the Tkinter tutorial covers menus &amp; toolbars in Tkinter">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container2">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content2">


<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Menus &amp; toolbars</h1>

<p>
In this part of the Tkinter tutorial, we will 
work with menus and toolbar. 
</p>

<div class="big_hor">
<script type="text/javascript"><!--
google_ad_client = "ca-pub-9706709751191532";
/* big_horizontal */
google_ad_slot = "2904953388";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<p>
A menubar is one of the most visible parts of the GUI application. 
It is a group of commands located in various menus. While in console 
applications you had to remember all those arcane commands, here we have 
most of the commands grouped into logical parts. There are accepted standards
that further reduce the amount of time spending to learn a new application.
Menus group commands that we can use in an application. 
Toolbars provide a quick access to the most frequently used commands.
</p>


<h2>Simple menu</h2>

<p>
The first example will show a simple menu. 
</p>

<pre class="code">
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode Tkinter tutorial

This program shows a simple
menu. It has one command, which
will terminate the program, when
selected. 

author: Jan Bodnar
last modified: December 2010
website: www.zetcode.com
"""

from Tkinter import Tk, Frame, Menu


class Example(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent        
        self.initUI()
        
    def initUI(self):
      
        self.parent.title("Simple menu")
        
        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)
        
        fileMenu = Menu(menubar)
        fileMenu.add_command(label="Exit", command=self.onExit)
        menubar.add_cascade(label="File", menu=fileMenu)
        

    def onExit(self):
        self.quit()


def main():
  
    root = Tk()
    root.geometry("250x150+300+300")
    app = Example(root)
    root.mainloop()  


if __name__ == '__main__':
    main()  
</pre>

<p>
Our example will show a menu with one item. By selecting the 
exit menu item we close the application. 
</p>

<pre class="explanation">
menubar = Menu(self.parent)
self.parent.config(menu=menubar)
</pre>

<p>
Here we create a menubar. It is a regular <code>Menu</code> widget configured
to be the menubar of the root window. 
</p>


<pre class="explanation">
fileMenu = Menu(menubar)
</pre>

<p>
We create a file menu object. A menu is a popup window containing commands.

</p>

<pre class="explanation">
fileMenu.add_command(label="Exit", command=self.onExit)
</pre>

<p>
We add a command to the file menu. The command will call the onExit() method.
</p>

<pre class="explanation">
menubar.add_cascade(label="File", menu=fileMenu)
</pre>

<p>
The file menu is added to the menubar. 
</p>

<img src="/img/gui/tkinter/simplemenu.png" alt="Simple menu">
<div class="figure">Figure: Simple menu</div>


<h2>Submenu</h2>

<p>
A submenu is a menu plugged into another menu object. 
The next example demonstrates this. 
</p>

<pre class="code">
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode Tkinter tutorial

In this script we create a submenu
a separator and keyboard shortcuts to menus.

author: Jan Bodnar
last modified: December 2010
website: www.zetcode.com
"""

from Tkinter import Tk, Frame, Menu


class Example(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent
        
        self.initUI()
        
    def initUI(self):
      
        self.parent.title("Submenu")
        
        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)
        
        fileMenu = Menu(menubar)       
        
        submenu = Menu(fileMenu)
        submenu.add_command(label="New feed")
        submenu.add_command(label="Bookmarks")
        submenu.add_command(label="Mail")
        fileMenu.add_cascade(label='Import', menu=submenu, underline=0)
        
        fileMenu.add_separator()
        
        fileMenu.add_command(label="Exit", underline=0, command=self.onExit)
        menubar.add_cascade(label="File", underline=0, menu=fileMenu)        
                

    def onExit(self):
        self.quit()


def main():
  
    root = Tk()
    root.geometry("250x150+300+300")
    app = Example(root)
    root.mainloop()  


if __name__ == '__main__':
    main()  
</pre>

<p>
In the example, we have three options in a submenu of a file menu. We create 
a separator and keyboard shortcuts.
</p>


<pre class="explanation">
submenu = Menu(fileMenu)
submenu.add_command(label="New feed")
submenu.add_command(label="Bookmarks")
submenu.add_command(label="Mail")
</pre>

<p>
We have a submenu with three commands. The submenu is a regular menu.
</p>

<pre class="explanation">
fileMenu.add_cascade(label='Import', menu=submenu, underline=0)
</pre>

<p>
By adding the menu to the fileMenu and not to the menubar, we create
a submenu. The underline parameter creates a keyboard shortcut. We provide
a character position, which should be underlined. In our case it is the
first. Positions start from zero. When we click on the File menu, a popup
window is shown. The Import menu has one character underlined. We can 
select it either with the mouse pointer, or with the Alt + I shortcut.  
</p>

<pre class="explanation">
fileMenu.add_separator()
</pre>

<p>
A separator is a horizontal line that visually separates the menu commands. 
This way we can group items into some logical places.
</p>


<img src="/img/gui/tkinter/submenu.png" alt="Submenu">
<div class="figure">Figure: Submenu</div>


<h2>Popup menu</h2>

<p>
In the next example, we create a popup menu. Popup menu is also
called a context menu. It can be shown anywhere on the client area
of a window. 
</p>

<pre class="code">
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode Tkinter tutorial

In this program, we create
a popup menu. 

author: Jan Bodnar
last modified: December 2010
website: www.zetcode.com
"""

from Tkinter import Tk, Frame, Menu


class Example(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent
        
        self.initUI()
        
    def initUI(self):
      
        self.parent.title("Popup menu")
        self.menu = Menu(self.parent, tearoff=0)
        self.menu.add_command(label="Beep", command=self.bell())
        self.menu.add_command(label="Exit", command=self.onExit)

        self.parent.bind("&lt;Button-3&gt;", self.showMenu)
        self.pack()
        
        
    def showMenu(self, e):
        self.menu.post(e.x_root, e.y_root)
       

    def onExit(self):
        self.quit()


def main():
  
    root = Tk()
    root.geometry("250x150+300+300")
    app = Example(root)
    root.mainloop()  


if __name__ == '__main__':
    main()  
</pre>

<p>
In our example, we create a popup menu with two 
commands. 
</p>

<pre class="explanation">
self.menu = Menu(self.parent, tearoff=0)
</pre>

<p>
A context menu is a regular <code>Menu</code> widget. The
<code>tearoff</code> feature is turned off. Now it is not possible
to separate the menu into a new toplevel window. 
</p>

<pre class="explanation">
self.parent.bind("&lt;Button-3&gt;", self.showMenu)
</pre>

<p>
We bind the &lt;Button-3&gt; event to the showMenu() method.
The event is generated when we right click on the client area
of the window. 
</p>


<pre class="explanation">
def showMenu(self, e):
    self.menu.post(e.x_root, e.y_root)
</pre>

<p>
The showMenu() method shows the context menu. The popup menu
is shown at the x, y coordinates of the mouse click. 
</p>

<img src="/img/gui/tkinter/popupmenu.png" alt="Popup menu`">
<div class="figure">Figure: Popup menu</div>



<h2>Toolbar</h2>

<p>
Menus group commands that we can use in an application. Toolbars provide 
a quick access to the most frequently used commands. There is no toolbar
widget in Tkinter. 
</p>

<pre class="code">
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode Tkinter tutorial

In this program, we create a toolbar.

author: Jan Bodnar
last modified: December 2010
website: www.zetcode.com
"""

from PIL import Image, ImageTk
from Tkinter import Tk, Frame, Menu
from Tkinter import Button, LEFT, TOP, X, FLAT, RAISED



class Example(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent
        
        self.initUI()
        
    def initUI(self):
      
        self.parent.title("Toolbar")
        
        menubar = Menu(self.parent)
        self.fileMenu = Menu(self.parent, tearoff=0)
        self.fileMenu.add_command(label="Exit", command=self.onExit)
        menubar.add_cascade(label="File", menu=self.fileMenu)
        
        toolbar = Frame(self.parent, bd=1, relief=RAISED)

        self.img = Image.open("exit.png")
        eimg = ImageTk.PhotoImage(self.img)  

        exitButton = Button(toolbar, image=eimg, relief=FLAT,
            command=self.quit)
        exitButton.image = eimg
        exitButton.pack(side=LEFT, padx=2, pady=2)
       
        toolbar.pack(side=TOP, fill=X)
        self.parent.config(menu=menubar)
        self.pack()
        
       
    def onExit(self):
        self.quit()


def main():
  
    root = Tk()
    root.geometry("250x150+300+300")
    app = Example(root)
    root.mainloop()  


if __name__ == '__main__':
    main()  
</pre>

<p>
Our toolbar will be a frame on which we will put a button.
</p>

<pre class="explanation">
toolbar = Frame(self.parent, bd=1, relief=RAISED)
</pre>

<p>
A toolbar is created. It is a <code>Frame</code>. We created a raised border,
so that the boundaries of a toolbar are visible. 
</p>

<pre class="explanation">
self.img = Image.open("exit.png")
eimg = ImageTk.PhotoImage(self.img)
</pre>

<p>
Image and a photo image for the toolbar button are created. 
</p>

<pre class="explanation">
exitButton = Button(toolbar, image=tatras, relief=FLAT,
    command=self.quit)
</pre>

<p>
<code>Button</code> widget is created. 
</p>

<pre class="explanation">
exitButton.pack(side=LEFT, padx=2, pady=2)
</pre>

<p>
The toolbar is a frame and a frame is a container widget.
We pack the button to the left side. We add some padding. 
</p>

<pre class="explanation">
toolbar.pack(side=TOP, fill=X)
</pre>

<p>
The toolbar itself is packed to the top of the toplevel window.
It is horizontally stretched. 
</p>

<img src="/img/gui/tkinter/toolbar.png" alt="Toolbar">
<div class="figure">Figure: Toolbar</div>


<p>
In this part of the Tkinter tutorial, we mentioned menus and toolbars. 
</p>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>

<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified January 8, 2011  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

